// 反馈收集云函数
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const { content, timestamp } = event

  // 参数验证
  if (!content || content.trim().length === 0) {
    return {
      success: false,
      message: '反馈内容不能为空'
    }
  }

  // 验证今日是否已提交过反馈
  try {
    const today = new Date()
    today.setHours(0, 0, 0, 0)

    const todaySubmissions = await db
      .collection('feedback')
      .where({
        openid: OPENID,
        createdAt: db.command.gte(today)
      })
      .count()

    if (todaySubmissions.total > 0) {
      return {
        success: false,
        message: '今日已提交过反馈'
      }
    }
  } catch (error) {
    console.error('检查今日提交失败', error)
  }

  // 保存反馈到数据库
  try {
    const result = await db.collection('feedback').add({
      data: {
        content: content.trim(),
        openid: OPENID,
        createdAt: db.serverDate(),
        timestamp: timestamp || Date.now(),
        status: 'unread' // 未读状态
      }
    })

    return {
      success: true,
      message: '反馈提交成功',
      _id: result._id
    }
  } catch (error) {
    console.error('保存反馈失败', error)
    return {
      success: false,
      message: '提交失败，请稍后重试',
      error: error.message
    }
  }
}
